<?php
class Pageley_Commerce_Command_FindArticles extends Pageley_Controller_Command_TransactionalRead {

    private $term;
    private $categoryId;

	protected function executeInternal() {
		$unitOfWork = $this->getUnitOfWork();
        $terms = Pageley_Util_String::split($this->term, "[ ]+");
        $nameConditions = new Pageley_Util_ArrayMap();
        $descriptionConditions = new Pageley_Util_ArrayMap();
        foreach($terms as $term) {
            $nameConditions->add(new Pageley_Query_Condition_Contains("name", $term));
            $descriptionConditions->add(new Pageley_Query_Condition_Contains("description", $term));
        }
        $condition = new Pageley_Query_Condition_OrGroup(
            new Pageley_Util_ArrayMap(
	            new Pageley_Query_Condition_AndGroup($nameConditions),
	            new Pageley_Query_Condition_AndGroup($descriptionConditions)
            ));
        if($this->categoryId !== null) {
            $category = $unitOfWork->find(Pageley_Commerce_Domain_Category::type(),
                $this->categoryId);
            $condition = new Pageley_Query_Condition_AndGroup(
                new Pageley_Util_ArrayMap(
                    new Pageley_Query_Condition_Equals("category", $category),
                    $condition
                ));
        }
		$query = new Pageley_Query_Basic(Pageley_Commerce_Domain_Article::type(),
		    $condition);
        $articles = $unitOfWork->query($query);
		$model = new Pageley_Util_ArrayMap();
		$model->put(Pageley_Commerce_Request::ARTICLES, $articles);
		return new Pageley_Controller_ModelAndView($model);
	}
    
    public function setTerm($term) {
        $this->term = $term;
    }
    
    public function setCategoryId($categoryId) {
        $this->categoryId = $categoryId;
    }
}